6

I have a text file and I would like to only delete the first character of the text file, is there a way to do this in shell script?

I'm new to writing scripts so I really don't know where to start. I understand that the main command most people use is "sed" but I can only find how to use that as a find and replace tool.

All help is appreciated.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
Ammastaro
  • 163
  • 1
  • 2
  • 12

6 Answers6

17

You can use the tail command, telling it to start from character 2:

tail -c +2 infile > outfile
Barmar
  • 741,623
  • 53
  • 500
  • 612
9

You can use sed

sed '1s/^.//' startfile > endfile
  • 1s means match line 1, in substitution mode (s)
  • ^. means at the beginning of the line (^), match any character (.)
  • There's nothing between the last slashes, which means substitute with nothing (remove)
ihatecsv
  • 532
  • 6
  • 20
  • 2
    here you don't need the `^`, the first char replaced is by definition is the first char. – karakfa May 30 '18 at 20:32
  • You don't even need to anchor with `^` - but you do need to do something different if the first character is a newline: `sed -e '1{' -e '/^$/d' -e 's/.//' -e '}'`. – Toby Speight May 31 '18 at 10:37
3

I used to use cut command to do this.

For example:

cat file|cut -c2-80

Will show characters from column 2 to 80 only.

In your case you can use:

cat file|cut -c2-10000 > newfile

I hope this help you.

[]s

2

You can also use the 0,addr2 address-range to limit replacements to the first substitution, e.g.

sed '0,/./s/^.//' file

That will remove the 1st character of the file and the sed expression will be at the end of its range -- effectively replacing only the 1st occurrence.

To edit the file in place, use the -i option, e.g.

sed -i '0,/./s/^.//' file

or simply redirect the output to a new file:

sed '0,/./s/^.//' file > newfile
David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
  • This only works if the first character is not a newline - you really need `/^$/d` within there for that case. – Toby Speight Nov 20 '18 at 08:53
  • @TobySpeight - not so. `'\n'` is a line ending and is not counted as a character. Give it a try `printf "\n\nCrackers&Cheese\n" | sed '0,/./s/^.//'` yields `"rackers&Cheese". I also note your solution fails for that very case. – David C. Rankin Nov 20 '18 at 15:20
  • Ah, so you're taking a record-oriented view of the word, where newlines are merely record separators? That wasn't obvious. – Toby Speight Nov 20 '18 at 16:33
2

A few other ideas:

awk '{print (NR == 1 ? substr($0,2) : $0)}' file

perl -0777 -pe 's/.//' file

perl -pe 's/.// unless $done; $done = 1' file

ed file <<END
1s/.//
w
q
END
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
2

dd allows you to specify an offset at which to start reading:

dd ibs=1 seek=1 if="$input" of="$output"

(where the variables are set to point to your input and output files, respectively)

Toby Speight
  • 27,591
  • 48
  • 66
  • 103