As I said before, using any of the following commands:
cat abc.txt > abc.txt
cat abc.txt | sed "any sed arguments" > abc.txt
sed "any sed arguments" abc.txt > abc.txt
will result in abc.txt
being a file of size 0, containing absolutely no characters. So, the code that you say is working on your Linux systems cannot possibly do what you say it is doing. The following should come close to what you said you want on a Linux distribution and on an AIX system:
#!/bin/bash
IAm=${0##*/}
file="abc.txt"
tmpfile="$IAm".$$
trap 'rm -rf "$tmpfile"' EXIT
line_number=1
current_value=MOHIT
new_value=Ankit
# Function to convert a string to a BRE that will match a case-insensitive
# version of that string.
# Usage: string2CIBRE "string"
string2CIBRE() {
awk -v s="$1" '
BEGIN { for(i = 1; i <= length(s); i++)
printf("%s", ((L = substr(s, i, 1)) ~ /[[:alpha:]]/) ? \
"[" tolower(L) toupper(L) "]" : L)
}
'
}
printf 'Contents of "%s" before sed:\n' "$file"
cat "$file"
sed "${line_number}s/$(string2CIBRE "$current_value")/$new_value/g" "$file" > "$tmpfile" &&
cp "$tmpfile" "$file"
printf '**********\nContents of "%s" after sed:\n' "$file"
cat "$file"
If abc.txt
contains the following before you run the above script:
Hello , My name is Mohit, all lowercase: mohit, all uppercase: MOHIT
I am learning shell script
Hello , My name is Mohit, all lowercase: mohit, all uppercase: MOHIT
I am learning shell script
the output from the above script will be:
Contents of "abc.txt" before sed:
Hello , My name is Mohit, all lowercase: mohit, all uppercase: MOHIT
I am learning shell script
Hello , My name is Mohit, all lowercase: mohit, all uppercase: MOHIT
I am learning shell script
**********
Contents of "abc.txt" after sed:
Hello , My name is Ankit, all lowercase: Ankit, all uppercase: Ankit
I am learning shell script
Hello , My name is Mohit, all lowercase: mohit, all uppercase: MOHIT
I am learning shell script
and, as indicated by the output, the contents of abc.txt
after running the script will be:
Hello , My name is Ankit, all lowercase: Ankit, all uppercase: Ankit
I am learning shell script
Hello , My name is Mohit, all lowercase: mohit, all uppercase: MOHIT
I am learning shell script
In addition to working with bash
, this should also work with a 1988 or a 1993 version of the Korn shell ( ksh
) or any other shell that performs basic POSIX shell required parameter expansions.