Можно использовать переименование Perl (, а не Linux ):
prename -n 's/(\d*)\s*foo_\d*/$1/g' /path/to/folder/*.ext
или
prename -n 's/(\d*)\s*.*_\d*/$1/g' /path/to/folder/*.ext
Примеры имен файлов:
100 foo_2.ext
101 foo_1.ext
200 foo_234.ext
302 foo_2.ext
Результаты:
100.ext
101.ext
200.ext
302.ext
Информация:
(\d)\sfoo_\d
или(\d)\s.*_\d
:соответствует имени вашего файла (\d)
:возвращает цифры впереди $1
:возвращаемое значение (s )переменная в2
-n
:используется для просмотра результата команды prename
, удалите, чтобы внести изменения См.:man prename
Хорошо, я сам нашел ответ...
на самом деле намного проще в php, чем без него...
правда, мне потребовалось много часов, чтобы закончить ^^
#load the file as simplexml object and then switch into system
#https://www.w3schools.com/php/func_simplexml_load_file.asp
$xml=simplexml_load_file('./myfile') or die("Error: Cannot create object");
$xml=$xml->system
#put the whole string(s) into a variable, getname gets the name of the object itself if it exists
#https://www.w3schools.com/php/func_simplexml_getname.asp
$output='type='. $xml -> type -> static -> getName(). $xml -> type -> {'dhcp-client'} -> getName(). "\nip-address=". $xml -> {'ip-address'}. "\ndefault-gateway=". $xml -> {'default-gateway'}. "\nnetmask=". $xml -> netmask;
#write the output into a file
#https://www.w3schools.com/php/func_filesystem_file_put_contents.asp
file_put_contents('./myoutputfile', $output );
это дало мне следующий вывод для первого фрагмента (последние три строки в порядке, если они не дают значения, в противном случае я мог бы сначала проверить, существуют ли они):
type=dhcp-client
ip-address=
default-gateway=
netmask=
и этот вывод для второго фрагмента:
type=static
ip-address=192.168.0.2
default-gateway=192.168.0.1
netmask=255.255.255.0
Спасибо всем за помощь:)
Следуя ответу отсюда https://stackoverflow.com/questions/893585/how-to-parse-xml-in-bash, я сделал простой скрипт
#!/bin/bash
read_dom () {
local IFS=\>
read -d \< ENTITY CONTENT
}
found=0
while read_dom; do
if [[ $ENTITY = "ip-address" ]] && [[ $last_tag = "/hostname" ]] || [[ $ENTITY = "netmask" ]] || [[ $ENTITY = "default-gateway" ]]; then
if [[ $found = 0 ]]; then
echo "type=static"
fi
echo "$ENTITY=$CONTENT"
found="1"
fi
last_tag=$ENTITY
done
if [[ $found = 0 ]]; then
echo "type=dhcp-client"
fi
Если вы назовете свой скрипт parse.sh
, вы можете назвать его так
parse.sh < input.xml > output.txt
Если предположить, что у вас нет доступа к инструменту, поддерживающему XML -, а ваш входной файл такой же простой и регулярный, как вы показываете, это дает ожидаемый результат из вашего опубликованного примера входных данных:
$ cat tst.awk
BEGIN { FS="[[:space:]]*[<>][[:space:]]*"; OFS="=" }
$2 == "system" { inBlock=1 }
inBlock { f[$2] = $3 }
$2 == "/system" { inBlock=0 }
END {
if ("ip-address" in f) {
print "type", "static"
print "ip-address", f["ip-address"]
print "default-gateway", f["default-gateway"]
print "netmask", f["netmask"]
}
else {
print "type", "dhcp-client"
}
}
.
$ awk -f tst.awk absentFile
type=dhcp-client
.
$ awk -f tst.awk presentFile
type=static
ip-address=192.168.0.2
default-gateway=192.168.0.1
netmask=255.255.255.0
Описанное выше было выполнено на этих входных файлах.:
$ tail -n +1 absentFile presentFile
==> absentFile <==
<deviceconfig>
<system>
<type>
<dhcp-client>
<send-hostname>yes</send-hostname>
</dhcp-client>
</type>
<hostname>Firewall</hostname>
</system>
</deviceconfig>
==> presentFile <==
<deviceconfig>
<system>
<type>
<static/>
</type>
<hostname>Firewall</hostname>
<permitted-ip>
<entry name="192.168.0.0/24"/>
</permitted-ip>
<ip-address>192.168.0.2</ip-address>
<netmask>255.255.255.0</netmask>
<default-gateway>192.168.0.1</default-gateway>
</system>
<network>
<interface>
<ethernet>
<entry name="ethernet1/1">
<layer3>
<ip>
<entry name="192.168.0.5/24"/>
</ip>
</layer3>
</entry>
</ethernet>
</interface>
<virtual-router>
<entry name="default">
<routing-table>
<ip>
<static-route>
<entry name="default-route">
<nexthop>
<ip-address>192.168.0.1</ip-address>
</nexthop>
<interface>ethernet1/4</interface>
<destination>0.0.0.0/0</destination>
</entry>
</static-route>
</ip>
</routing-table>
</entry>
</virtual-router>
</network>
Вы можете использовать следующий скриптip-parse.sh
:
#!/bin/bash
#https://stackoverflow.com/questions/22221277/bash-grep-between-two-lines-with-specified-string
#https://www.cyberciti.biz/faq/bash-remove-whitespace-from-string/
#https://stackoverflow.com/questions/1251999/how-can-i-replace-a-newline-n-using-sed
sed -n '/\<system\>/,/system\>/p' ~/Desktop/x-test.xml | sed -e 's/^[ \t]*//' > ~/Desktop/x-system.xml
sed ':a;N;$!ba;s/\n/ /g' ~/Desktop/x-system.xml > /tmp/xml-one-line.xml
#[]test to see if the "system" section...
#... has the word hostname occuring before the word ip-address
#https://stackoverflow.com/questions/33265650/grep-for-a-string-in-a-specific-order
if [ -n "$(grep hostname.*ip-address /tmp/xml-one-line.xml)" ]; then
echo "File contains hostname and ip-address, in that order."
else
echo "type=dhcp-client" ; echo "type=dhcp-client" > ~/Desktop/network-config.txt ; exit
fi
#http://www.compciv.org/topics/bash/variables-and-substitution/
ipaddress="$(grep ip-address ~/Desktop/x-system.xml | sed 's/<ip-address>//g; s/<\/ip-address>//g')"
defaultgateway="$(grep default-gateway ~/Desktop/x-system.xml | sed 's/<default-gateway>//g; s/<\/default-gateway>//g')"
netmask="$(grep netmask ~/Desktop/x-system.xml | sed 's/<netmask>//g; s/<\/netmask>//g')"
echo "type=static" > ~/Desktop/network-config.txt
echo "ip-address=$ipaddress" >> ~/Desktop/network-config.txt
echo "default-gateway=$defaultgateway" >> ~/Desktop/network-config.txt
echo "netmask=$netmask" >> ~/Desktop/network-config.txt
Пример применения:
paul@mxg6:~/Desktop$./ip-parse.sh
File contains hostname and ip-address, in that order.
paul@mxg6:~/Desktop$ cat network-config.txt
type=static
ip-address=192.168.0.2
default-gateway=192.168.0.1
netmask=255.255.255.0
Если вам не нужно проверять, стоит ли имя хоста перед ip -адресом, и вы хотите использовать переменные вместо промежуточных файлов, попробуйте это:
#!/bin/bash
xsystemxml="$(sed -n '/\<system\>/,/system\>/p' ~/Desktop/x-test.xml \
| sed -e 's/^[ \t]*//')"
if [ -n "$(echo $xsystemxml | grep ip-address)" ]; then
echo "System section contains ip-address."
else
echo "type=dhcp-client"
echo "type=dhcp-client" > ~/Desktop/network-config.txt
exit
fi
ipaddress="$(echo "$xsystemxml" | grep "ip-address" \
| sed 's/<ip-address>//g; s/<\/ip-address>//g')"
defaultgateway="$(echo "$xsystemxml" | grep "default-gateway" \
| sed 's/<default-gateway>//g; s/<\/default-gateway>//g')"
netmask="$(echo "$xsystemxml" | grep "netmask" \
| sed 's/<netmask>//g; s/<\/netmask>//g')"
echo "type=static" > ~/Desktop/network-config.txt
echo "ip-address=$ipaddress" >> ~/Desktop/network-config.txt
echo "default-gateway=$defaultgateway" >> ~/Desktop/network-config.txt
echo "netmask=$netmask" >> ~/Desktop/network-config.txt
Вот сценарий bash, использующий файл sed.
scriptname input.xml
Вывод отправляется на стандартный вывод
#!/bin/bash
sed -n '{
/<hostname>/ {
# next line makes a comment out of hostname
# add a '#' to beginning of line to supress
s/\s*<hostname>\(.\+\)<\/hostname>/# \1/p #make hostname into a comment with hash
n # read next line to patern space
/<ip-address>/{ # if this line contains <ip-address>
i\type=static
s/\s\{1,\}<\(ip-address\)>\(.\+\)<\/\1>/\1=\2/p
n # read next line to patern space
# netmask
s/\s\{1,\}<\(netmask\)>\(.\+\)<\/\1>/\1=\2/p
n # read next line to patern space
# default-gateway
s/\s\{1,\}<\(default-gateway\)>\(.\+\)<\/\1>/\1=\2\n/p
n
b end # branch to end
}
/<ip-address>/ !{ # if line does not contain with <ip-address>
i\type=dhcp-client\
}
:end # end label
}
}
' $1