Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I replace the last character of a string with another character in bash?

Tags:

string

bash

shell

I am working on a small code in bash, but I am stuck on a small problem. I have a string, and I want to replace the last letter of that string with s.

For example: I am taking all the files that end in c and replacing the last c with s.

for file in *.c; do
   # replace c with s  
   echo $file

Can someone please help me?

like image 617
user2709885 Avatar asked Oct 03 '13 21:10

user2709885


People also ask

How do you change the last character of a string?

replace() method to replace the last character in a string, e.g. const replaced = str. replace(/. $/, 'replacement'); . The replace method will return a new string with the last character replaced by the provided replacement.

How do I replace a character with another character in Unix?

To replace one character in a string with another character, we can use the parameter extension in Bash (shell). Here is an example that removes the character a with b in the following string. Similarly, you can also replace multiple characters in the string with a single character like this.

How can I remove last character from a string in Unix?

You can also use the sed command to remove the characters from the strings. In this method, the string is piped with the sed command and the regular expression is used to remove the last character where the (.) will match the single character and the $ matches any character present at the end of the string.

How do I replace a character in a file in Bash?

To replace content in a file, you must search for the particular file string. The 'sed' command is used to replace any string in a file using a bash script. This command can be used in various ways to replace the content of a file in bash. The 'awk' command can also be used to replace the string in a file.


2 Answers

for file in *.c; do 
   echo "${file%?}s"
done

In parameter substitution, ${VAR%PAT} will remove the last characters matching PAT from variable VAR. Shell patterns * and ? can be used as wildcards.

The above drops the final character, and appends "s".

like image 161
Henk Langeveld Avatar answered Oct 26 '22 13:10

Henk Langeveld


Use parameter substitution. The following accomplishes suffix replacement. It replaces one instance of c anchored to the right with s.

for file in *.c; do
   echo "${file/%c/s}"  
done
like image 41
iruvar Avatar answered Oct 26 '22 14:10

iruvar