Basic operations using Awk and Sed
March15
awk and sed
Swap the columns using the sed and awk
1 2 3 4 5 | $ echo "A B" | sed 's/\(.\) \(.\)/\2 \1/' B A $ echo "A B" | awk '{print $2,$1}' B A |
Replace the first occurance of “AA” with “ZZ”
1 2 3 4 5 | $ echo "ABCDAB" | awk '{sub("AB","ZZ",$0)}1' ZZCDAB $ echo "ABCDAB" | sed 's/AB/ZZ/' ZZCDAB |
Replace all the occruances of “AA” to “ZZ”
1 2 3 4 5 | $ echo "ABCDAB" | awk '{gsub("AB","ZZ",$0)}1' ZZCDZZ $ echo "ABCDAB" | sed 's/AB/ZZ/g' ZZCDZZ |
Print all the charcters with space delimited
1 2 3 4 5 | $ echo "ABCDAB" | awk -v FS= '{for(i=1;i<=NF;i++){printf("%s ",$i)}}' A B C D A B $ echo "ABCDAB" | sed 's/./& /g' A B C D A B |
Print the 2nd line of the test.txt file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | $ cat test.txt one two three four five $ sed -n '2p' test.txt two $ awk 'NR==2' test.txt two $ sed '2!d' test.txt two |
Print all the lines except the 2nd line
1 2 3 4 5 6 7 8 9 10 11 | $ sed '2d' test.txt one three four five $ awk 'NR!=2' test.txt one three four five |
Print the 2nd,3rd and 4th line in the test.txt file
1 2 3 4 5 6 7 8 | $ sed -n '2,4p' test.txt two three four $ awk 'NR>1&&NR <strong>Replace the wore "one" to "two" in the 2nd line of the file.</strong> |
1 2 3 4 5 6 7 8 9 10 11 12 13 | $ sed -e '2 s/one/two/' test.txt one two three four five $ awk 'NR==2{sub("one","two",$0)}1' test.txt one two three four five |
Recent Comments