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

BashUnixCommandTruncate

Bash Problem Overview


For example, I might want to:

tail -f logfile | grep org.springframework | <command to remove first N characters>

I was thinking that tr might have the ability to do this but I'm not sure.

Bash Solutions


Solution 1 - Bash

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-

Solution 2 - Bash

sed 's/^.\{5\}//' logfile 

and you replace 5 by the number you want...it should do the trick...

EDIT if for each line sed 's/^.\{5\}//g' logfile

Solution 3 - Bash

You can use cut:

cut -c N- file.txt > new_file.txt

-c: characters

file.txt: input file

new_file.txt: output file

N-: Characters from N to end to be cut and output to the new file.

Can also have other args like: 'N' , 'N-M', '-M' meaning nth character, nth to mth character, first to mth character respectively.

This will perform the operation to each line of the input file.

Solution 4 - Bash

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

would remove the first 900 characters

cut uses 900- to show the 900th character to the end of the line

however when I pipe all of this through grep I don't get anything

Solution 5 - Bash

I think awk would be the best tool for this as it can both filter and perform the necessary string manipulation functions on filtered lines:

tail -f logfile | awk '/org.springframework/ {print substr($0, 6)}'

or

tail -f logfile | awk '/org.springframework/ && sub(/^.{5}/,"",$0)'

Solution 6 - Bash

Here is simple function, tested in bash. 1st param of function is string, 2nd param is number of characters to be stripped

function stringStripNCharsFromStart { echo ${1:$2:${#1}} }

Usage: enter image description here

Solution 7 - Bash

x=hello

echo ${x:1}

returns ello

replace 1 with N as required

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionles2View Question on Stackoverflow
Solution 1 - BashiammichaelView Answer on Stackoverflow
Solution 2 - BashLB40View Answer on Stackoverflow
Solution 3 - BashAnkurView Answer on Stackoverflow
Solution 4 - Bashles2View Answer on Stackoverflow
Solution 5 - BashJohn BView Answer on Stackoverflow
Solution 6 - BashTo KraView Answer on Stackoverflow
Solution 7 - BashMarkView Answer on Stackoverflow