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.)

+2


source to share


4 answers


This simple script answers your questions:

awk '/Line-to-reorder/ {tmp = $1; $1 = $3; $3 = tmp} {print}' file.txt

      



  • you can assign fields to edit row
  • not necessary cat

  • prints (all fields) every line
+3


source


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.

+2


source


This link can help

+1


source


the best option will probably match all lines (no picture) and then execute if ... else

in action.

something like

{
if ($0 ~ /Line-to-reorder/)
    print $3 $2 $1
else
    print $0
}

      

+1


source







All Articles