9

I would like to know how i can delete the first column of a csv file with awk or sed

Something like this :

FIRST,SECOND,THIRD

To something like that

SECOND,THIRD

Thanks in advance

0

4 Answers 4

28

Following awk will be helping you in same.

awk '{sub(/[^,]*/,"");sub(/,/,"")} 1'   Input_file

Following sed may also help you in same.

sed 's/\([^,]*\),\(.*\)/\2/'  Input_file

Explanation:

awk '                 ##Starting awk code here.
{
  sub(/[^,]*/,"")     ##Using sub for substituting everything till 1st occurence of comma(,) with NULL.
  sub(/,/,"")         ##Using sub for substituting comma with NULL in current line.
}
1                     ##Mentioning 1 will print edited/non-edited lines here.
'   Input_file        ##Mentioning Input_file name here.
3
  • 2
    2 sub calls can be combined into one by sub(/[^,]*,/,"")
    – anubhava
    Sep 19, 2020 at 9:33
  • Why does'nt the command sub(/,/,"") remove all the comma? Oct 23, 2023 at 14:29
  • Because it's sub its designed to remove only 1 comma, on other hand gsub us for Global substitution which can remove all commas. Oct 23, 2023 at 14:32
1

Using awk

$awk -F, -v OFS=, '{$1=$2; $2=$3; NF--;}1' file
SECOND,THIRD
1

Using sed : ^[^,]+, regex represent the first column including the first comma. ^ means start of the line, [^,]+, means anything one or more times but a comma sign followed by a comma.

you can use -i with sed to make changes in file if needed.

sed -r 's/^[^,]+,//' input
SECOND,THIRD 
2
  • Without the -r option : sed 's/^[^,]*,//' input
    – ctac_
    Oct 24, 2017 at 8:35
  • This one worked for me, sed 's/[^,]*,//' Nov 25, 2020 at 4:24
1

With Sed

sed -i -r 's@^\w+,@@g' test.csv

Grab the begin of the line ^, every character class [A-Za-z0-9] and also underscore until we found comma and replace with nothing. Adding g after delimiters you can do a global substitution.

3
  • I doubt if this will give the correct answer. .* means greedy match so you are going to replace till last comma.
    – P....
    Oct 24, 2017 at 7:44
  • Sorry, my bad, i have updated the code. Oct 24, 2017 at 7:48
  • This has been marked as low-quality for length and content. Would you mind elaborating a bit on your suggested command. What are the switches for? ...
    – Fildor
    Oct 24, 2017 at 8:09

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