0

I have a scenario where want data to be stored in file in vertical format

below is the data

143|2345|3456|4567|2345|3457|2019-12-28 12:00:01|2019-12-28

After applying my below logic my data is in below format

cat demo.txt |rev| cut -d'|' -f3-|rev|cut -d'|' -f2-

It gives me the required output like below

2345|3456|4567|2345|3457

But now the issue is i want the required output data in vertical format to a text file

like below in file

2345
3456
4567
2345
3457
1
  • Do you have a file with several such rows in? Is the number of columns consistent? Seems to me the answers posted so far retain the first field, or remove the last 2 fields from only the final record, or other kinds of bad. Dec 28, 2019 at 10:41

3 Answers 3

1
tr '|' '\n'

will convert each pipe to a newline and should do the trick.

echo "143|2345|3456|4567|2345|3457|2019-12-28 12:00:01|2019-12-28" | tr '|' '\n'

Or maybe in your case you're looking for

cat file | tr '|' '\n' > newfile
1

To work with multiple rows, and with a variable number of fields, this removes col1 and the last two columns, and puts remaining columns vertically.

awk '-F|' '{ for (f = 2; f <= NF - 2; ++f) print $(f); }' data.txt
0

Using your original data and GNU head:

$ tr '|' '\n' <demo.txt | head -n -2
143
2345
3456
4567
2345
3457

The tr command just changes |-characters into newlines. Note that tr only reads from standard input, so you will need to redirect into it.

If GNU head is given a negative number of lines, it trims that number of lines off from the end of the data.

Alternatively, with a single call to sed:

$ sed 's/\(|[^|]*\)\{2\}$//; y/|/\n/' demo.txt
143
2345
3456
4567
2345
3457

Here, the substitution will remove the last two |-delimited fields by matching the two |-characters and the strings after each, then the y command changes each remaining | into a newline (just like tr does in the first solution).

With sed -E, it may be a bit more readable (note that we have to escaep one of the |-characters now):

sed -E 's/(\|[^|]*){2}$//; y/|/\n/' demo.txt

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .