40

How would I remove the first word from each line of text in a stream?

For example,

$ cat myfile
some text 1
some text 2
some text 3

I want:

$ cat myfile | magiccommand
text 1
text 2
text 3

How would I go about this using Bash? I could use awk '{print $2 $3 $4 $5 ....}', but that's messy and would result in extra spaces for all null arguments. I was thinking that sed might be able to do this, but I could not find any examples of this.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Trcx
  • 4,164
  • 6
  • 30
  • 30
  • Somewhat related: *[How can I retrieve the first word of the output of a command in Bash?](https://stackoverflow.com/questions/2440414)* – Peter Mortensen Apr 25 '21 at 22:39

5 Answers5

84

Based on your example text,

cut -d' ' -f2- yourFile

should do the job.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kent
  • 189,393
  • 32
  • 233
  • 301
  • 5
    Caution: I tried using this to remove the indexing on the output of `history` and it doesn't work at the start of history due to the spaces before the smaller numbers acting as delimiters. – Jason Doucette Jul 18 '18 at 17:43
  • @JasonDoucette different input formats may need different solutions – Kent Jul 19 '18 at 07:36
13

That should work:

$ cat test.txt
some text 1
some text 2
some text 3

$ sed -e 's/^\w*\ *//' test.txt
text 1
text 2
text 3
Yanick Girouard
  • 4,711
  • 4
  • 19
  • 26
11

Here is a solution using awk

awk '{$1= ""; print $0}' yourfile 
vk239
  • 1,014
  • 1
  • 12
  • 30
6

Run this:

sed "s/^some\s//g" myfile

You even don't need to use a pipe.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
3

To remove the first word, until space no matter how many spaces exist, use: sed 's/[^ ]* *//'

Example:

$ cat myfile 
some text 1
some  text 2
some     text 3

$ cat myfile | sed 's/[^ ]* *//'
text 1
text 2
text 3
Benny
  • 2,233
  • 1
  • 22
  • 27