Delete the First Five Characters on Any Line of a Text File in Linux with Sed

Delete the first five characters on any line of a text file in Linux with sed

sed 's/^.....//'

means

replace ("s", substitute) beginning-of-line then 5 characters (".") with nothing.

There are more compact or flexible ways to write this using sed or cut.

How to delete first n characters from each first line of multiple files using bash?

try this:

#!/bin/bash
for file in ./*.json; do
sed -i '1s/.*/{/' "$file"
done

explanation

# loop over all *.json files in current directory 
for file in ./*.json; do

# -i use inplace replacement
# replace first line with '{'
sed -i '1s/.*/{/' "$file"
done

How do I remove first 5 characters in each line in a text file using vi?

:%s/^.\{0,5\}// should do the trick. It also handles cases where there are less than 5 characters.

What is a unix command for deleting the first N characters of a line?

Use cut. Eg. to strip the first 4 characters of each line (i.e. start on the 5th char):

tail -f logfile | grep org.springframework | cut -c 5-

delete first n characters of a very large file in unix shell

You can use:

sed -i.bak -r '1s/^.{10}//' file

This will create a backup file.bak and remove the first 10 characters from the first line. Note -i alone can also be used, to do in-place edit without backup.

Test

Original file:

$ cat a
1234567890some bad data and here we are
blablabla
yeah

Let's:

$ sed -i.bak -r '1s/^.{10}//' a
$ cat a
some bad data and here we are
blablabla
yeah
$ cat a.bak
1234567890some bad data and here we are
blablabla
yeah

Command to trim the first and last character of a line in a text file

$ cat /tmp/txt
xyyyyyyyyyyyyyyyyyyyx
pyyyyyyyyyyyyyyyyyyyz

$ sed 's/^.\(.*\).$/\1/' /tmp/txt
yyyyyyyyyyyyyyyyyyy
yyyyyyyyyyyyyyyyyyy

How to delete from a text file, all lines that contain a specific string?

To remove the line and print the output to standard out:

sed '/pattern to match/d' ./infile

To directly modify the file – does not work with BSD sed:

sed -i '/pattern to match/d' ./infile

Same, but for BSD sed (Mac OS X and FreeBSD) – does not work with GNU sed:

sed -i '' '/pattern to match/d' ./infile

To directly modify the file (and create a backup) – works with BSD and GNU sed:

sed -i.bak '/pattern to match/d' ./infile


Related Topics



Leave a reply



Submit