1

Lets say I have fields:

name, number, id

I have a data file:

name1|number1|id1|name2|number2|id2...etc

I want to replace every 3rd pipe with a new line or '\n' so I get:

name1|number1|id1  
name2|number2|id2  

I'm having no luck with awk or sed.

I've tried the following, and variations of:

awk '/"\|"/{c++;if(c==10){sub("\|","\n");c=0}}1' inputfile.txt  
sed 's/"|"/"\n"/2' inputfile.txt  

It tells me awk:

syntax error near line 1

awk: illegal statement near line 1

awk: syntax error near line 1

awk: bailing out near line 1

Any help is greatly appreciated!

EDIT: Thank you!

3

You can for example use this:

$ awk -v RS="|" '{printf $0 (NR%3?RS:"\n")}' file
name1|number1|id1
name2|number2|id2..

Explanation

  • -v RS="|" sets the record separator as |.
  • printf $0 (NR%3?RS:"\n") print the full line with a new line in case the number of record is multiple of 3.
1

A pure bash answer. Not as elegant as the awk solution, but may come in handy:

i=3; IFS='|'; while read -a line; do echo "${line[*]:0:$i}"; echo "${line[*]:$i}"; done < inputfile.txt

Explanation:

  • i=3 Set this to the number of fields you want per line.
  • IFS='|' Sets the delimiter to pipe.
  • while read -a line Read each line from the input file into a bash array.
  • echo "${line[*]:0:$i}" Print the first $i values of the array on a line.
  • echo "${line[*]:$i}" Print the rest of the array on a line.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.