Skip to content
Advertisement

sed substitute with partial string

echo "/c/test/my0.txt" | sed 's/.{5}$/.{4}$/g'

Is it possible to replace the last 5 characters of the line with the last 4 characters of the line in sed?

My filenames can be any length but the end is always predictable i.e. the part I want to substitute is always 5 characters from the end

Advertisement

Answer

Just match them separately, and omit the undesired character:

echo "/c/test/my0.txt" | sed 's/.(....)$/1/'

Another approach to what you seem to be after: You could explicitly target the last character before the filename suffix; this would work correctly even if the suffix had more, or fewer, characters (.mpeg, .c, .txt~, etc.)

echo "/c/test/my0.txt~" | sed 's/..([^.][^.]*)$/.1/'

With sed -E (recommended), you can use the standard “modern” regular expressions and write the last one as:

echo "/c/test/my0.txt~" | sed -E 's/..([^.]+)$/.1/'
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement