How can I selectively awk a string?
If the text lines of undefined width in the file had the text "Line-reorder" and I only wanted to flip and display the order of the first three tokens I can do:
# cat file.txt | awk '/Line-to-reorder/ { print $3 $2 $1 }'
How do I allow lines of text that do not meet the matching criteria to pass through unmodified?
Second, how can I display the remainder of the tokens (the remainder of the string) on ββthe appropriate line?
(awk is the tool of choice, since my busybox builtin has it.)
source to share
No need to do if...else
, just do match / not match.
This prints fields 3, 2, and 1, and then the rest of the fields in original order if the string matches. If it is not, it prints the entire line as is.
awk '/Line-to-reorder/ {printf "%s %s %s", $3, $2, $1; for (i=4; i<=NF; i++) {printf " %s", $i }; printf "\n"} !/Line-to-reorder/ {print}' file.txt
Broken down into awk
script:
#!/usr/bin/awk -f
/Line-to-reorder/ {
printf "%s %s %s", $3, $2, $1
for (i=4; i<=NF; i++) {
printf " %s", $i
}
printf "\n"
}
!/Line-to-reorder/ {print}
Run this with something like:
awkscript file.txt
This awk
script takes a filename as an argument (because it awk
does), so cat
it is not required for either method to call.
source to share