When it comes to command line text processing, from an abstract point of view, there are three major pillars



Download 125.91 Kb.
Page5/60
Date09.03.2023
Size125.91 Kb.
#60849
1   2   3   4   5   6   7   8   9   ...   60
Learn GNU AWK

Substitution


awk has three functions to cover search and replace requirements. Two of them are shown below. The sub function replaces only the first match whereas gsub function replaces all the matching occurrences. By default, these functions operate on $0 when the input string isn't provided. Both sub and gsub modifies the input source on successful substitution.
$ # for each input line, change only first ':' to '-' $ # same as: sed 's/:/-/' $ printf '1:2:3:4\na:b:c:d\n' | awk '{sub(/:/, "-")} 1' 1-2:3:4 a-b:c:d $ # for each input line, change all ':' to '-' $ # same as: sed 's/:/-/g' $ printf '1:2:3:4\na:b:c:d\n' | awk '{gsub(/:/, "-")} 1' 1-2-3-4 a-b-c-d
The first argument to sub and gsub functions is the regexp to be matched against the input content. The second argument is the replacement string. String literals are specified within double quotes. In the above examples, sub and gsub are used inside a block as they aren't intended to be used as a conditional expression. The 1 after the block is treated as a conditional expression as it is used outside a block. You can also use the variations presented below to get the same results.

  • awk '{sub(/:/, "-")} 1' is same as awk '{sub(/:/, "-"); print $0}'

  • You can also just use print instead of print $0 as $0 is the default string
You might wonder why to use or learn grep and sed when you can achieve same results with awk. It depends on the problem you are trying to solve. A simple line filtering will be faster with grep compared to sed or awk because grep is optimized for such cases. Similarly, sed will be faster than awk for substitution cases. Also, not all features easily translate among these tools. For example, grep -o requires lot more steps to code with sed or awk. Only grep offers recursive search. And so on. See also unix.stackexchange: When to use grep, sed, awk, perl, etc.

Download 125.91 Kb.

Share with your friends:
1   2   3   4   5   6   7   8   9   ...   60




The database is protected by copyright ©ininet.org 2024
send message

    Main page