0

I'd like to extract the 2nd field and transpose it to become a row

cat > temp1
1   73
2   74
3   75

My approach :

cut -f2 temp1 | tr '\n'  '\t' > temp2

The result :

temp2
73  74  75  

Understandably, there is a tab separator at the right end of the line but missing a new line character. Is there an simple one-liner to fix this?

3 Answers 3

1

Use paste instead of tr:

$ cut -f2 temp1 | paste -s
73  74  75

verifying the invisible whitespace

$ cut -f2 temp1 | paste -s | od -c
0000000   7   3  \t   7   4  \t   7   5  \n
0000011
0
1
  cat file | cut -d' ' -f2 | xargs -n3
  73 74 75

and to verify the invisible whitespace per @glenn jackman

cat file | cut -d' ' -f4 | xargs -n3 |  od -c

0000000   7   3       7   4       7   5  \n
0000011
0

The simplest way to print/emit/give a new line is to use echo.

It seems quite simple to add a new line to the file created:

cut -f2 temp1 | tr '\n' '\t' > temp2 echo >> temp2

Which could be done in one line as:

{ cut -f2 temp1 | tr '\n'  '\t' ; echo ; } > temp2

That is: if the trailing tab is not a problem. If it is, you need to either remove it or avoid it being generated, any of this will do it:

awk 'NR>1{printf( "%s\t",a)}{a=$2}END{print a}' temp1 >temp2

sed -n 's/[0-9]*[[:blank:]]*//;1{h;d};H;${g;y/\n/\t/;p}' temp1 >temp2

sed 's/[0-9]*[[:blank:]]*//' temp1 | paste -sd '\t' >temp2

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.