Reputation: 51
In the text file I've to move the rows matching the country name with the information.
Sample text is:
U.S.A
Washington English 9,372,610 sq km
France
Paris French 547,030 sq km
Desired o/p:
U.S.A Washington English 9,372,610 sq km
France Paris French 547,030 sq km
Is there any way I can do this using sed or by using awk?
Upvotes: 0
Views: 50
Reputation: 77075
Using sed
:
$ sed 'N;s/\n/ /' file
U.S.A Washington English 9,372,610 sq km
France Paris French 547,030 sq km
Append the next line to pattern space using N
which is separated by a \n
followed by a simple substitution to replace the \n
with space.
Using awk
:
$ awk '{ORS=(NR%2?FS:RS)}1' file
U.S.A Washington English 9,372,610 sq km
France Paris French 547,030 sq km
Set the Output Record Separator to space for every line except second line where you set it to newline using Record Separator.
Using paste
:
$ paste -d " " - - < file
U.S.A Washington English 9,372,610 sq km
France Paris French 547,030 sq km
-d " "
sets the delimiter to space. - -
allows us to buffer two lines from the file and print it together separated by the delimiter.
Upvotes: 3
Reputation: 3575
If the lines are cleanly interleaved as pairs, you could separate both kinds of lines in two files, and then paste them together left and right:
$ <countries.txt grep ' sq km$' > countries-loc.txt
$ <countries.txt grep -v -e ' sq km$' -e '^$' > countries-state.txt
$ paste -d ' ' countries-state.txt countries-loc.txt
U.S.A Washington English 9,372,610 sq km
France Paris French 547,030 sq km
Cleaning up multiple spaces, and spaces on start of line:
$ paste -d ' ' countries-state.txt countries-loc.txt | tr -s ' ' | sed 's/^ //'
U.S.A Washington English 9,372,610 sq km
France Paris French 547,030 sq km
Upvotes: 1