Write a sed command that deletes the second character in each line in a file.

sed -e 's/^.//' sample 

The above command deletes the first character. But how do you specify the second character alone?

sed 's/.//2' sample

The trailing 2 is a "flag" for the s command in sed (just like the sometimes over-used g is) and it instructs sed to only act on the 2nd match of the regular expression on each line. Since the regular expression is . (matches any single character), this would remove the second character from each line of input.

In general, any positive integer may be used after the final / delimiter of the s command to skip forward some matches on a line.

  • TIL sed regex substitute can take a count like this!
    – filbranden
    Aug 11 '19 at 13:46
  • @filbranden Yes, and GNU sed allows for combining an integer with g. This lets you do silly things like deleting every second character with sed 's/.\(.\)/\1/2g'. That's a GNU extension though.
    – Kusalananda
    Aug 11 '19 at 13:59

If your sed supports backreferences:

sed -E 's/^(.)./\1/'

In your specific case

You can use the following rule

sed 's/.//2' sample

where 2 correspdonds to the 2nd character.

As an example for a dummy input file called test.txt


the output of the sed 's/.//2' test.txt command is


As a general rule

You can can remove the Nth character of the pattern . (i.e. all characters) by using

sed 's/.//N' sample

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.