0

How can I replace two characters, 5th and 6th digit in the string below?

 2xxx99xx

I want to replace 5th and 6th digit (which is 99) by getting the record count of the file.

 $cat file | wc -l
 3

The output must be:

 2xxx03xx
4
  • 1
    Could possibly be done with sed, or awk, or many other programs. You might want to try yourself first, and tell us what you tried and how it went. Commented Oct 21, 2014 at 2:10
  • 1
    wc -l < file is preferable to cat file | wc -l. Commented Oct 21, 2014 at 2:23
  • @Joachim Pileborg, i tried this record_count=wc -l < $FILE FOO=2xxx03xx awk -v rec="${record_count}" ' { data = substr ($0, 5, 6); data=rec; print }' but nothing changes with FOO. Sorry I am new to this. Commented Oct 21, 2014 at 3:30
  • Where is the string 2xxx99xx stored? In a variable? In a file? Piped from some other command? Do you want the original file or variable to be modified or do you just want to see the updated string in stdout? Please clarify. Commented Oct 21, 2014 at 3:54

2 Answers 2

3
foo=2xxx99xx
printf "%s%02d%s" ${foo:0:4} $(wc -l < file) ${foo:6}
Sign up to request clarification or add additional context in comments.

4 Comments

I got this error ${trailer:0:4}: The specified substitution is not valid for this command. Please note that trailer=$(tail -n 1 $FILES)
What does tail -n 1 $FILES print for you?
This is the printed output: 20019923
Works perfectly for me. Maybe if you post your entire script that doesn't work...otherwise it seems like there's something wrong in a piece you aren't showing us.
0

With sed:

echo "2xxx99xx" | sed -r "s/(.{4})..(.*)/\1$(printf "%02d" `wc -l < ff`)\2/g"

first 4 characters form group 1, rest of the string except 5th and 6th characters form group 2. Then we put back the 1st group, formatted data, then the 2nd group.

If the sed version doesn't support extended regex, use below command:

echo "2xxx99xx" | sed "s/\(.\{4\}\)..\(.*\)/\1$(printf "%02d" `wc -l < ff`)\2/g"

4 Comments

How if I got a 4-digit record count. For example, I got 4567 record count, how can I get 2x4567xx?
what are the other possiblities? if u have 45678, do u need output to be 245678xx?. if u have 456789, do u need output to be 456789xx?
Yes exactly, it should replace preceding digits.
Yes exactly, it should replace preceding digits

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.