0

so my input is as following:

1,somerandomwordsx,some.random.words,random.numbers.word,random
2,somerandoms,random,randomnumber,
1,randomwords,word1,word2,word3
21,randomwords,words.random,unique.word,more.random.words
111,randomword1,random.word2

Output should be

1,somerandomwordsx,some.random.words,random.numbers.word,random
1,randomwords,word1,word2,word3

I tried many ways with awk, grep, sed, but either it ignores commas or it includes every "1," match, including "111," which it should not, only the line with the exact number 1 in the first column should be saved.

Thanks for help!

1

Using awk:

$ awk -F , '$1 == 1' file
1,somerandomwordsx,some.random.words,random.numbers.word,random
1,randomwords,word1,word2,word3

With awk we may read each line as a set of fields delimited by commas. The code above prints all lines where the first field ($1) is exactly 1.

Using sed:

$ sed '/^1,/!d' file
1,somerandomwordsx,some.random.words,random.numbers.word,random
1,randomwords,word1,word2,word3
$ sed -n '/^1,/p' file
1,somerandomwordsx,some.random.words,random.numbers.word,random
1,randomwords,word1,word2,word3

Using grep:

$ grep '^1,' file
1,somerandomwordsx,some.random.words,random.numbers.word,random
1,randomwords,word1,word2,word3

With sed and grep we may use the regular expression ^1, which means "the character 1 at at start of the line, followed by a comma". The ^ anchors the expression to the start of the line, and by matching a comma after the 1 we avoid matching lines that start with 11 or 12 etc.

The first sed variation removes all lines that does not match this pattern while the other prints only lines that matches the pattern. The effect is the same.

1
  • Oh man, thanks for confirming that these are the actual options which I tried all and that didnt work. And guess what, it didn't work as well and then I figured out, the file format is bugged, all lines were actually only one single line. So, I fixed the file format and everything works now. Thanks a lot!
    – MaerzIT
    Aug 27 at 10:04

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.