1

I have roughly 7 columns on each line, I want to print two specific columns then the remaining columns after the last specified one, example:

awk -F: {' print $2 ":" $6 '} a.txt

would print columns 2 and 6 from a.txt. How would I then go onto print the remaining columns after $6?

So example of input/output would be:

    column2:column6:column7:column8:column9... 
2

4 Answers 4

2

You could use cut instead: echo 1:2:3:4:5:6:7:8:9:10|cut -d: -f 2,6-.

1

This does what you want if you have to use awk:

$ awk 'BEGIN{FS=":"; OFS=":"}{$1=$3=$4=$5="";gsub("^"FS,"",$0);gsub(FS"+",FS,$0)}1' <your file>
  • The above works by splitting everything into fields via BEGIN{FS=":"; OFS=":"}.
  • It then clears fields 1,3,4, & 5, by setting them to "".
  • The 2 gsub commands clean things up by removing any colons (:) that may start at the beginning. = The 2nd gsub removes any sequences of colons (:) from the remaining string in $0.
  • Lastly we print the results via the 1.
0
 perl -F: -pale '$"=":"; $_ = "@F[1,5..$#F]"' input-file.txt

 awk -F: '
    {
       a = $2
       for ( i = 6; i <= NF; ++i )
          $(i-5) = $(i)
       NF -= 5
       print a, $0
    }
 ' OFS=":" input-file.txt

 sed -e '
    s/^/:/;s/:/\n/6
    h;s/.*\n//
    x;s/\n.*//
    s/$/:/
    s/^://;s/:/\n/2
    s/^/:/;s/:/\n/2
    s/.*\n\(.*\)\n.*/\1/
    G;s/\n/:/
  '  input-file.txt
0

You can use a for loop to count from the starting index until the last index and concatenate a variable which gets printed at the end:

TEST_STRG="column1:column2:column3:column4:column5:column6:column7:column8:column9"
echo $TEST_STRG | awk 'BEGIN {FS=":"} {out=$2; for(i = 6; i <= NF; i++) out = out""FS""$i } END {print out}'
  • out=$2: initializes the variable with the 2nd column
  • i <= NF: "NF" is the "number of fields" -> the amount of columns resulting by splitting the input
  • out = out""FS""$i: concatenates the column at the current index to the variable after the field separator "FS"

This will result in the output: column2:column6:column7:column8:column9

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.