• Bash脚本学习:AWK, SED


    1. AWK

    AWK 是一种编程语言,设计用于处理文件或数据流中基于文本的数据,或者使用 shell 管道。 可以将 awk 与 shell 脚本结合使用或直接在 shell 提示符下使用。
    在这里插入图片描述

    • 以上展示使用AWK分别打印第一个位置变量和第二个位置变量。

    建立一个文档 csvtest.csv。
    文档内容为:
    one, two, three

    awk -F, '{print $1}' csvtest.csv
    
    • 1

    输出为:one

    • 提取并打印每一行的第一个字段
    • -F,:这是awk命令的选项,用于指定字段分隔符。在这里,-F, 表示字段之间使用逗号,作为分隔符,因为CSV文件中通常使用逗号来分隔不同的字段。
    echo "Just get this word: Hello" | awk '{print $5}'
    
    • 1
    • 以上打印第5个字段,即是"Hello"。
    echo "Just get this word: Hello" | awk -F: '{print $2}' | cut -c2-
    
    • 1
    • -F:选项指定了字段分隔符为冒号:,然后’{print $2}'表示打印第二个字段。
    • cut -c2-:最后,cut命令被用于删除输出中的第一个字符(即空格)。-c2-选项表示从第二个字符开始截取到末尾,因此最终的输出是:“Hello”。
     echo "Just get this word: Hello" | awk -F: '{print $2}' | cut -c2
    
    • 1
    • cut -c2:最后,cut命令被用于提取输出中的第二个字符,即字母"H"。-c2选项表示提取第二个字符。

    2. SED

    Sed 主要用来自动编辑一个或多个文件、简化对文件的反复操作、编写转换程序等。
    在sedtest.txt文本中,输入文件内容:
    The fly flies like no fly flies.
    A fly is an insect that has wings and a fly likes to eat leftovers.

    在指令行:

    sed 's/fly/grasshopper/g' sedtest.txt
    
    • 1

    输出为:
    The grasshopper flies like no grasshopper flies.
    A grasshopper is an insect that has wings and a grasshopper likes to eat leftovers.

    • 以上使用s/old_text/new_text/g的编辑格式,其中old_text是要查找的文本,new_text是要替换成的文本,而g表示全局匹配,即查找并替换每个匹配的实例。在这个命令中,它将所有出现的"fly"替换为"grasshopper"。
    sed -i.ORIGINAL 's/fly/grasshopper/g' sedtest.txt
    
    • 1
    • -i.ORIGINAL:这是sed命令的选项,它表示进行原地编辑,并且将原始文件备份为.ORIGINAL的扩展名。这意味着在编辑文件之前,sed会先创建一个备份文件,以防止意外的数据损坏。

    所以现在有两个文件:
    ① sedtest.txt.ORIGINAL
    The fly flies like no fly flies.
    A fly is an insect that has wings and a fly likes to eat leftovers.

    ② sedtest.txt
    The grasshopper flies like no grasshopper flies.
    A grasshopper is an insect that has wings and a grasshopper likes to eat leftovers.

  • 相关阅读:
    Lightsail VPS 实例在哪些方面胜过 EC2 实例?
    隐秘而伟大——纪念图灵诞辰110周年
    【无标题】std::thread
    微信小程序底部安全区域高度获取
    余弦定理的证明
    Python 自动化测试框架unittest与pytest的区别
    C语言 字符数组
    foil算法
    【云原生之kubernetes实战】在k8s集群下helm工具的安装与使用
    AcWing-C/C++语法基础【合集2】
  • 原文地址:https://blog.csdn.net/weixin_57266891/article/details/132945274