user2008558
user2008558

Reputation: 341

Remove last character from a file in unix

Have

08-01-12|07-30-13|08-09-32|12-43-56|

Want

08-01-12|07-30-13|08-09-32|12-43-56

I want to remove just the last |.

Upvotes: 0

Views: 3965

Answers (2)

NeronLeVelu
NeronLeVelu

Reputation: 10039

quick and dirty

sed 's/.$//' YourFile

a bit secure

sed 's/[|]$//' YourFile

allowing space

sed 's/[|][[:space:]]*$//' YourFile

same for only last char of last line (thansk @amelie for this comment) : add a $in front so on quick and dirty it gives sed '$ s/.$//' YourFile

Upvotes: 5

fedorqui
fedorqui

Reputation: 289525

Since you tagged with awk, find here two approaches, one for every interpretation of your question:

  • If you want to remove | if it is the last character:

    awk '{sub(/\|$/,"")}1' file
    

Equivalent to sed s'/|$//' file, only that escaping | because it has a special meaning in regex content ("or").

  • If you want to remove the last character, no matter what it is:

    awk '{sub(/.$/,"")}1' file
    

Equivalent to sed s'/.$//' file, since . matches any character.

Test

$ cat a
08-01-12|07-30-13|08-09-32|12-43-56|
rrr.
$ awk '{sub(/\|$/,"")}1' a
08-01-12|07-30-13|08-09-32|12-43-56
rrr.                                 # . is kept
$ awk '{sub(/.$/,"")}1' a
08-01-12|07-30-13|08-09-32|12-43-56
rrr                                  # . is also removed

Upvotes: 1

Related Questions