rommedahl
rommedahl

Reputation: 21

Concatenation of two columns from the same file

From a text file

file

a    d
b    e
c    f

how are the tab delimited columns concatenated into one column

a
b
c
d
e
f

Now I use awk to output columns to two files that I then concatenated using cat. But there must be a better one line command?

Upvotes: 1

Views: 1108

Answers (7)

Unwastable
Unwastable

Reputation: 679

another approach:

for i in $(seq 1 2); do
    awk '{print $'$i'}' file
done

output:

a
b
c
d
e
f

Upvotes: -1

karakfa
karakfa

Reputation: 67467

for a generalized approach

$ f() { awk '{print $'$1'}' file; }; f 1; f 2

a
b
c
d
e
f

if the file is tab delimited perhaps simply with cut (the inverse operation of paste)

$ cut -f1 file.t; cut -f2 file.t

Upvotes: 2

dawg
dawg

Reputation: 103744

You can combine bash commands with ; to get a single stream:

$ awk '{print $1}' file; awk '{print $2}' file
a
b
c
d
e
f

Use process substitution if you want that to be as if it were a single file:

$ txt=$(awk '{print $1}' file; awk '{print $2}' file)
$ echo "$txt"
a
b
c
d
e
f

Or for a Bash while loop:

$ while read -r line; do echo "line: $line"; done < <(awk '{print $1}' file; awk '{print $2}' file)
line: a
line: b
line: c
line: d
line: e
line: f

Upvotes: 0

anubhava
anubhava

Reputation: 784968

This simple awk command should do the job:

awk '{print $1; s=s $2 ORS} END{printf "%s", s}' file
a
b
c
d
e
f

Upvotes: 1

RavinderSingh13
RavinderSingh13

Reputation: 133438

try: Without reading file twice or without any external calls of any other commands, only single awk to rescue. Also considering that your Input_file is same like shown sample.

awk '{VAL1=VAL1?VAL1 ORS $1:$1;VAL2=VAL2?VAL2 ORS $2:$2} END{print VAL1 ORS VAL2}'   Input_file

Explanation: Simply creating a variable named VAL1 which will contain $1's value and keep on concatenating in it's own value, VAL2 will have $2's value and keep on concatenating value in it's own. In END section of awk printing the values of VAL1 and VAL2.

Upvotes: 0

riteshtch
riteshtch

Reputation: 8769

You can use process substitution; that would eliminate the need to create file for each column.

$ cat file 
a    d
b    e
c    f
$ cat <(awk '{print $1}' file) <(awk '{print $2}' file)
a
b
c
d
e
f
$ 

OR

as per the comment you can just combine multiple commands and redirect their output to a different file like this:

$ cat file 
a    d
b    e
c    f
$ (awk '{print $1}' file; awk '{print $2}' file) > output
$ cat output 
a
b
c
d
e
f
$

Upvotes: 0

Elliott Marshall
Elliott Marshall

Reputation: 39

If you're using notepadd++ you could replace all tab values with the newlenter image description hereine char "\r\n"

Upvotes: -1

Related Questions