I am writing a bash script in which I want to replace the first digit if 0 with 92 and if there is no 0 and 92 append 92 in front of that digit and save it in a new file.
Any help would be appreciated.
Below is my bash script:
scrap.sh
#!/bin/bash
file=test.txt
while IFS=, read -r field1
do
echo $field1 | awk '$0*=1'>> test2.txt
done < $file
test.txt
03333333333
3848123249
expected output
923333333333
923848123249
With just bash parameter expansion:
$ while IFS= read -r line; do printf '92%s\n' "${line#0}"; done < test.txt
923333333333
923848123249
${line#0} removes a leading zero only if it exists.
https://www.gnu.org/software/bash/manual/bash.html#Shell-Parameter-Expansion
With your shown samples, please try following awk code.
awk '{$0=substr($0,1,1)==0?"92" substr($0,2):"92" $0} 1' Input_file
Explanation: Simple explanation would be, using awk's substr function to get sub strings from current line. In main program of awk re-assigning values to current line($0) based on conditions. Checking condition if 1st character is 0 then make $0 value to 92 and rest of line from 2nd character ELSE add 92 before $0. Finally mentioning 1 will print current edited/non-edited line.
Assuming this is your input file:
cat file
03333333333
92123456789
3848123249
You can use this sed:
sed -E '/^92/!s/0|^/92/' file
923333333333
92123456789
923848123249
sed command details:
/^92/! do this for the lines that don't start with 92/0|^/: Match first 0 or start position of a line/92/: Replace with 92 at start positionAn equivalent awk would be:
awk '!/^92/ {sub(/0|^/, "92")} 1' file