0

I need a linux bash script that can replace the spaces in name="this is a test".

example:

<input name="this is a test" id="testing 1 2 3" />

would change to this:

<input name="thisisatest" id="testing 1 2 3" />

EDIT: The script must be able to match anything between the double quotes. It could be this:

<input name="THIS STRING WILL VARY" id="testing 1 2 3" />

Any ideas?

1
  • Would a Python solution be a valid answer - it's tagged as such, but you're asking for a bash script... Commented Jul 20, 2013 at 14:38

4 Answers 4

3

Using Python - to take an HTML file, and remove spaces from input tags that have a name attribute equal to this is a test, you can use:

from bs4 import BeautifulSoup

with open('input') as fin, open('output', 'w') as fout:
    soup = BeautifulSoup(fin.read())
    for tag in soup.find_all('input', {'name': 'this is a test'}):
        tag['name'] = tag['name'].replace(' ', '')
    fout.write(str(soup))

In response to:

I forgot to say that the string "this is a test" can be anything

You can just filter out all input tags that have a name attribute and apply whatever logic you want - the below will remove spaces from any name attribute:

for tag in soup.find_all('input', {'name': True}):
    tag['name'] = tag['name'].replace(' ', '')
2
  • I forgot to say that the string "this is a test" can be anything. Commented Jul 20, 2013 at 15:11
  • @user2602373 updated to show how to find and replace any input tag with a name attribute - put whatever logic you want in it... Commented Jul 20, 2013 at 15:14
0
>>> name = 'this is a test'
>>> ''.join(name.split())
'thisisatest'
1
  • 1
    Doesn't explain how to replace in a file, but what's wrong with name.replace(' ','') anyway? Commented Jul 20, 2013 at 14:40
0

You can use sed:

foo='<input name="this is a test" id="testing 1 2 3" />'
echo $foo | sed 's/this is a test/thisisatest/'

If you want to do this in a file and save it, you can do this:

sed 's/this is a test/thisisatest/' filename > filename
1
  • I forgot to say that the string "this is a test" can be anything. It must match name="THIS TEXT CAN VARY" Commented Jul 20, 2013 at 15:12
0

Here's an awk one-liner

awk '
    BEGIN {FS=OFS="\""} 
    {for (f=2; f<=NF; f++) if ($(f-1) ~ /name=$/) gsub(/ /, "", $f)} 
    1
' file

It uses double quotes as the field separator. A quoted string will therefore be an odd-numbered field.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.