简体   繁体   中英

awk - how to delete first column with field separator

I have a csv file with data presented as follows

87540221|1356438283301|1356438284971|1356438292151697
87540258|1356438283301|1356438284971|1356438292151697
87549647|1356438283301|1356438284971|1356438292151697

I'm trying to save the first column to a new file (without field separator , and then delete the first column from the main csv file along with the first field separator.

Any ideas?

This is what I have tried so far

awk 'BEGIN{FS=OFS="|"}{$1="";sub("|,"")}1'

but it doesn't work

This is simple with cut :

$ cut -d'|' -f1 infile
87540221
87540258
87549647

$ cut -d'|' -f2- infile
1356438283301|1356438284971|1356438292151697
1356438283301|1356438284971|1356438292151697
1356438283301|1356438284971|1356438292151697

Just redirect into the file you want:

$ cut -d'|' -f1 infile > outfile1

$ cut -d'|' -f2- infile > outfile2 && mv outfile2 file 

假设您的原始 CSV 文件名为“orig.csv”:

awk -F'|' '{print $1 > "newfile"; sub(/^[^|]+\|/,"")}1' orig.csv > tmp && mv tmp orig.csv

GNU awk

awk '{$1="";$0=$0;$1=$1}1' FPAT='[^|]+' OFS='|'

Output

1356438283301|1356438284971|1356438292151697
1356438283301|1356438284971|1356438292151697
1356438283301|1356438284971|1356438292151697

Pipe is special regex symbol and sub function expectes you to pass a regex. Correct awk command should be this:

awk 'BEGIN {FS=OFS="|"} {$1=""; sub(/\|/, "")}'1 file

OUTPUT:

1356438283301|1356438284971|1356438292151697
1356438283301|1356438284971|1356438292151697
1356438283301|1356438284971|1356438292151697

使用sed

sed 's/[^|]*|//' file.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM