Operating System - HP-UX
1753501 Members
4882 Online
108794 Solutions
New Discussion юеВ

File content checking and replacing it!

 
SOLVED
Go to solution
Pando
Regular Advisor

File content checking and replacing it!

I have a file which contain the line
...
...
"-"
...
...
I need to get the "-" part to be passed to a variable ad subsequently replaced it by "9999". How can i get it in a single command?

Maximum points for correct reply!
3 REPLIES 3
H.Merijn Brand (procura
Honored Contributor
Solution

Re: File content checking and replacing it!

A variable to the changing process, or to the calling shell?

# perl -pi -e's{"(.*?)"}{"9999"} and $perl_var = $1' file

would change the content of file and have the variable available just after the change in perl as $perl_var

If it is only one line that is changed, and you want to promote the variable to the shell, you need to catch it and set it

# MY_VAR=`(perl -pi -e's{<(SUBID)>"(.*?)"}{<$1>"9999"} and print STDERR "$2\n"' file) 2>&1`

As a proof of concept:
--8<---
sh-2.05b$ MY_VAR=2
sh-2.05b$ echo $MY_VAR
2
sh-2.05b$ cat file
Line 1

Line 3
"1234"

Line 6
sh-2.05b$ MY_VAR=`(perl -pi -e's{<(SUBID)>"(.*?)"}{<$1>"9999"} and print STDERR "$2\n"' file) 2>&1`
sh-2.05b$ echo $MY_VAR
1234
sh-2.05b$ cat file
Line 1

Line 3
"9999"

Line 6
sh-2.05b$
-->8---

Enjoy, Have FUN! H.Merijn
Enjoy, Have FUN! H.Merijn
Elmar P. Kolkman
Honored Contributor

Re: File content checking and replacing it!

For the replacing you simply can use sed:
sed 's|".*"|"9999"'

But since you also want the old value in a variable, it gets trickier.

You could do something like this:

oldvalues=$(sed -n '/".*"<\/SUBID>/s|.*"\(.*\)".*|\1|p' input)
sed 's|".*"|"9999"|' input > output

This means, of course, that you run twice through the input file with sed...
Every problem has at least one solution. Only some solutions are harder to find.
Pando
Regular Advisor

Re: File content checking and replacing it!

Thanks for that quick reply.