Search code examples
awkgrepcut

Remove '||'(double pipe) separated multiple columns from file using shell script command


Please suggest perfect shell script command to remove last two '||' delimiter separated columns from the file.(Lets assume below example) File Name: abc.dat

"a1"||"a2"||"a3"||"a4"
"b1"||"b2"||"b3"||"b4"
"c1"||"c2"||"c3"||"c4"

output should be like :

"a1"||"a2"
"b1"||"b2"
"c1"||"c2"

I tried below cut and awk command but not worked:

awk -F '||' '{print $1$2}'  ${file} >> ${file}
cut -d'||' -f2 --complement ${file} >> ${file} (not working as cut: the delimiter must be a single character)

Solution

  • Rather than assuming || is the delimiter, assume that | is the delimiter and the second field is empty.

    $ cut -d'|' -f1-3 <<EOF
    > "a1"||"a2"||"a3"||"a4"
    > "b1"||"b2"||"b3"||"b4"
    > "c1"||"c2"||"c3"||"c4"
    > EOF
    "a1"||"a2"
    "b1"||"b2"
    "c1"||"c2"
    

    (This assumes that || was chosen for some aesthetic reason, rather than to allow for single pipes in each field.)