BAT 腳本
1、相互調用
1.1、bat 調用 python
bat批處理執行python 的幾種方式 ———— 批處理, python打包成 exe文件
@echo off
C:
cd C:\Users\ldl\Desktop
start python test100.py
start python 1.py
start python 1.py 10
start python 1.py 100
exit
1.2、bat 調用 bat
-
兩個bat文件在同一個目錄下
call b.bat
-
兩個bat文件不在同一個目錄下
先使用cd /d 目錄來進入相應的目錄,接着再call就行了
2、系統相關
2.1、不關閉
pause
2.2、讀取環境變量
echo
查看java_home環境變量
echo %java_home%
查看path環境變量
echo %path%
set
查看java_home環境變量
set java_home
3、文件操作
3.1、讀取
在批處理腳本中讀取文件是通過使用 FOR
循環命令來完成文件中需要讀取的每一行。 由於沒有直接的命令從文件中讀取文本到變量中,所以需要使用 for
循環來達到這個目的。
示例
@echo off
FOR /F "tokens=* delims=" %%x in (new.txt) DO echo %%x
delims
參數用於將文件中的文本分解為不同的標記或單詞。 每個單詞或標記然后存儲在變量x中。 對於從文件讀取的每個單詞,都會進行回顯以將單詞打印到控制台輸出。
其他參考鏈接:https://www.hxstrive.com/article/805.htm
3.2、判斷文件是否存在
@echo off
@title copy sth to current filepath
mode con lines=5 cols=40
SET SourceFile=123.txt
SET GenFile1=456.txt
if exist %SourceFile% (
if not exist %GenFile1% (
copy %SourceFile% %GenFile1%
) else (
echo %GenFile1% is exist!
)
) else (
echo %SourceFile% is not exist!
)
echo Success
ping -n 3 127.0.0.1 > nul
3.3、刪除文件及文件夾
1) 刪除文件
del命令參數說明
/F 強制刪除只讀文件。
/S 從所有子目錄刪除指定文件。
/Q 安靜模式。刪除全局通配符時,不要求確認。
/A 根據屬性選擇要刪除的文件。
2) 刪除目錄
rd 的另外一個寫法是rmdir
RD [/S] [/Q] [drive:]path
RMDIR [/S] [/Q] [drive:]path
/S 除目錄本身外,還將刪除指定目錄下的所有文件。用於刪除目錄樹。
/Q 安靜模式,帶 /S 刪除目錄樹時不要求確認
3) 創建目錄。
MKDIR [drive:]path
MD [drive:]path
如果需要,MKDIR 會在路徑中創建中級目錄。
mkdir \a\b\c\d
5、輸出打印
5.1、打印空行
用 echo 加空格、單引號、雙引號是不行的。
用 echo.,緊接着O后面加一個點,實現輸出空行。
6、字符串處理
6.1、字符串分割
@echo off
::定義一個以分號作為分隔的字符串
set str=AAA;BBB;CCC;DDD;EEE;FFF
::str的副本
set remain=%str%
:loop
for /f "tokens=1* delims=;" %%a in ("%remain%") do (
::輸出第一個分段(令牌)
echo %%a
rem 將截取剩下的部分賦給變量remain,其實這里可以使用延遲變量開關
set remain=%%b
)
::如果還有剩余,則繼續分割
if defined remain goto :loop
pause
6.2、字符串查找
Bat批處理中的 FIndstr用法
windows bat批處理腳本 字符串截取、拼接、查找等使用說明
批處理-字符串操作(截取、替換、合並)
findstr:
- 指定多個字符串和一個文件,打印找到的行:findstr "hello world" Test1.txt
- 指定多個字符串和多個文件,打印找到的行:findstr "hello world" Test1.txt Test2.txt
- 將"hello world"作為一個整體來查找:findstr /C:"hello world" Test1.txt--------這個比較關鍵,可以
- 只打印文件中完全匹配字符串的行:findstr /C:"hello world" /X Test1.txt
- 只打印不匹配的行:findstr /C:"hello world" /X /V Test1.txt
- findstr中的字符串支持正則表達式,可以使用/R來指定,此時字符串編程正則表達式。findstr /R "world$" Test1.txt
SHELL 腳本
1、查找
1.1 讀取正數第n行和倒數第n行
cat a.sh | tail -n +2 | head -n 1
cat a.sh | tail -n 2 | head -n 1
1.2 查找某字符串 在文件的行數
https://blog.csdn.net/whatday/article/details/105066031
grep -n "xxx" str.txt | head -1 | cut -d ":" -f 1 # 提取首次匹配的行號
2、替換
2.1、替換文件夾中所有滿足條件文件中的字符串
grep -rl "uint32_t" ./wireless_onoff_oem/ | xargs sed -i "s:uint32_t:u32:g"
grep -rl "uint16_t" ./wireless_onoff_oem/ | xargs sed -i "s:uint16_t:u16:g"
grep -rl "uint8_t" ./wireless_onoff_oem/ | xargs sed -i "s:uint8_t:u8:g"
grep -rl "int32_t" ./wireless_onoff_oem/ | xargs sed -i "s:int32_t:s32:g"
grep -rl "int16_t" ./wireless_onoff_oem/ | xargs sed -i "s:int16_t:s16:g"
grep -rl "int8_t" ./wireless_onoff_oem/ | xargs sed -i "s:int8_t:s8:g"
2.2、文件夾內文件批量個性修改
for file in *.json
do
autoid=`echo "$file" | sed 's:\(..\)E.*:\1:g'`
echo $autoid
if [ $autoid -gt 99 ]
then
rm $file
else
cp $file "1"$file
sed -i 's:"id".*:"id"\:"1'$autoid'":g' "1"$file
fi
done
3、磁盤操作
3.1、分區與格式化
列出:
➜ ~ sudo fdisk -l
Disk /dev/mmcblk0: 1.89 GiB, 2002780160 bytes, 3911680 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x4edc62da
Device Boot Start End Sectors Size Id Type
/dev/mmcblk0p1 2048 3911679 3909632 1.9G b W95 FAT32
分區:
➜ ~ sudo fdisk /dev/mmcblk0
a.在此狀態下輸入“m”可以查看幫助
b.在此狀態下輸入“d” 刪除已經存在的分區,第一次可跳過,如果要重新分區就需要。
c.在此狀態下輸入“p” 查看已經存在的分區
d.在此狀態下輸入“n” 新增分區,根據提示需要輸入分區號,之后還需要輸入分區大小
e.在此狀態下輸入“t” 改變文件系統格式,命令“l”顯示對應文件系統格式的id(提示上也有這個說明)
f.在此狀態下輸入“w” 保存分區兵退出
格式化:
分區完了還沒完成,還需要對分區進行格式化。需要注意的是要看下是否被系統mount了,如果有的話要先umount設備
sudo mkfs.ext4 /dev/mmcblk0p1
4、 比較
4.1、比較的基礎知識
1) 基本語法
shell的if語法和C語言等高級語言非常相似,唯一需要注意的地方就是shell的if語句對空格方面的要求比較嚴格(其實shell對所有語法的空格使用都比較嚴格),如果在需要空格的地方沒有打上空格,都會報錯。如if [ $1x == "ip"x ];then echo "abc";fi中少一個空格都會報錯。另外shell的if語句必須以fi作為結尾,不然同樣會報錯。
有else和elif時也一樣,需要注意空格的問題,下面這個例子可以作為參考:
if [ $1x == "ab"x ]; then
echo "you had enter ab"
elif [ $1x == "cd"x ]; then
echo "you had enter cd"
else
echo "you had enter unexpected word"
fi
2) 對比
介紹完if語句的基本語法后,if還有一個值得我們注意的地方,那就是"對比"。在C語言等高級語言中,不管是對比字符串、還是對比整型、浮點數等等數據類型,都是使用==、<=等等對比運算符就可以完成。但是在shell中對比字符串和對比數字,卻是要分開兩種方式。
對比字符串只能使用==、<、>、!=、-z、-n。對比字符串時,末尾一定要加上x(或者a、b等)一個字符,因為if [ $1x == "ab"x ]時如果沒有了x ,並且$1是"",這個語句會翻譯成if [ == "ab" ],左邊相當於沒有東西了,會報語法錯誤。或者使用[[ ]],就不需要x了。使用<或者>時,如果是用[ ],需要用轉義符"",如>。
對比數字使用既能使用-eq、-ne、-gt、-ge、-lt、-le,也能使用==、<、>、!=。其中-eq的意思是equal,-ne是unequal,-gt是greater than,-ge是greater than or equal to,-lt是less than,-le是less than or equal to。
3)使用正則表達式
if在對比時可以使用正則表達式,如if [[ $1 == aa ]](或者if [ $1x == aax ])。如果使用""把aa包圍起來,就會變成字符,而不是正則表達式中的。
4)[和[[的區別
區別一。在[中使用邏輯運算符,需要使用-a(and)或者-o(or)。在[[中使用邏輯運算符,需要使用&&或者||。
區別二。[是shell命令,在它包圍的表達式是它的命令行參數,所以串比較符>和<需要轉義,否則就變成io重定向了。[[是shell關鍵字,不會做命令行擴展,所以<和>不需要進行轉義。但是語法相對嚴格,如在[中可以用引號括起操作付,[[則不行。如if [ "-z" "ab" ]。
區別三。[[可以做算術擴展,[則不行。如if [[ 11+1 -eq 100 ]],而if [ 11+1 -eq 100 ]則會報錯。
5)文件判斷
在高級語言中,判斷文件是否存在等各種狀態都是需要調用特定的函數進行判斷。而在shell中,這方面就比較方便些,只需要運算符即可。
常用的文件判斷運算符如下:
-e 文件是否存在
-f 文件是否是普通文件(不是目錄、設備文件、鏈接文件)
-s 表示文件大小不為0
-d 表示文件是否是目錄
-b 表示是塊設備(光驅、軟盤等)
-c 表示是字符設備(鍵盤、聲卡等)
-p 表示是管道
-h 表示是符號鏈接
-S 表示是否是socket
-r、-w、-x表示文件是否有可讀、可寫、可執行權限(指運行這個測試命令的用戶)
f1 -nt f2 f1是否比f2新(new than)
f1 -ot f2 f1是否比f2舊(old than)
f1 -ef f2 f1和f2是否是相同文件的硬鏈接
```language
使用!時表示上述結果取反,由於內容較多,這里不一一列舉了。下面一個例子可以作為編程參考
myfile="aa.txt"
if [ ! -f $myfile ]; then
echo $myfile" is not exist"
touch $myfile
else
echo $myfile" is exist"
fi
if [ ! -s $myfile ]; then
echo "hello, my master" > $myfile
else
echo $myfile" is not null"
fi
PYTHON 腳本
1、基本資料
1.1、指導文檔
2、相互調用
3、函數相關
3.1、向文件傳參
[root@Test ~]# cat /opt/python.py
#!/usr/local/bin/python
# -*- coding:utf-8 -*-
import sys
print(sys.argv[0]) #sys.argv[0] 類似於shell中的$0,但不是腳本名稱,而是腳本的路徑
print(sys.argv[1]) #sys.argv[1] 表示傳入的第一個參數,既 hello
#運行結果:
[root@Test ~]# python /opt/python.py hello
/opt/python.py #打印argv[0] 腳本路徑
hello #打印argv[1] 傳入的參數 hello
4、文件操作
4.1、文件夾拷貝
Copy directory contents into a directory with python [duplicate]
from distutils.dir_util import copy_tree
# copy subdirectory example
fromDirectory = "/a/b/c"
toDirectory = "/x/y/z"
copy_tree(fromDirectory, toDirectory)
4.2、查找文件
Find all files in a directory with extension .txt in Python
You can use glob:
import glob, os
os.chdir("/mydir")
for file in glob.glob("*.txt"):
print(file)
or simply os.listdir:
import os
for file in os.listdir("/mydir"):
if file.endswith(".txt"):
print(os.path.join("/mydir", file))
or if you want to traverse directory, use os.walk:
import os
for root, dirs, files in os.walk("/mydir"):
for file in files:
if file.endswith(".txt"):
print(os.path.join(root, file))
4.3、刪除文件
shutil.copyfile( src, dst) #從源src復制到dst中去。 如果當前的dst已存在的話就會被覆蓋掉
shutil.move( src, dst) #移動文件或重命名
shutil.copymode( src, dst) #只是會復制其權限其他的東西是不會被復制的
shutil.copystat( src, dst) #復制權限、最后訪問時間、最后修改時間
shutil.copy( src, dst) #復制一個文件到一個文件或一個目錄
shutil.copy2( src, dst) #在copy上的基礎上再復制文件最后訪問時間與修改時間也復制過來了,
類似於cp –p的東西
shutil.copy2( src, dst) #如果兩個位置的文件系統是一樣的話相當於是rename操作,只是改名;
如果是不在相同的文件系統的話就是做move操作
shutil.copytree( olddir, newdir, True/Flase) #把olddir拷貝一份newdir,如果第3個參數是True,
則復制目錄時將保持文件夾下的符號連接,如果第3個參數是False,則將在復制的目錄下生成物理副本
來替代符號連接
shutil.rmtree( src ) #遞歸刪除一個目錄以及目錄內的所有內容
5、數據結構
5.1 SET
Get unique values from a list in python [duplicate]
mylist = ['nowplaying', 'PBS', 'PBS', 'nowplaying', 'job', 'debate', 'thenandnow']
myset = set(mylist)
print(myset)
6、字符串
6.1、基礎知識
Python 字符串
Python 字典(Dictionary)
6.2、XML 操作
xml.etree.ElementTree — The ElementTree XML API
How to write XML declaration using xml.etree.ElementTree
Insert xml element as first child using ElementTree in python
一個例子(可以實現自動遍歷目錄,向 Keil5 工程文件中插入 .c.h.lib 的邏輯)
def create_subgroup(UVPROJX_PATH,GROUP_NAME,SOURCES_ROOT,KIND,OFFSET_PATH):
tree = ET.parse(UVPROJX_PATH)
root = tree.getroot()
if KIND == '.c' or KIND == '.lib':
Groups = root.find("Targets").find("Target").find("Groups")
Group = ET.Element('Group')
GroupName = ET.SubElement(Group, 'GroupName')
GroupName.text = GROUP_NAME
Files = ET.SubElement(Group, 'Files')
kind_map = {'.c' : '1', '.lib' : '4'}
for root, dirs, files in os.walk(SOURCES_ROOT):
for file in files:
if file.endswith(KIND):
print(os.path.join(OFFSET_PATH+"\\"+root, file))
File = ET.SubElement(Files, 'File')
FileName = ET.SubElement(File, 'FileName')
FileName.text = file
FileType = ET.SubElement(File, 'FileType')
FileType.text = kind_map[KIND]
FilePath = ET.SubElement(File, 'FilePath')
FilePath.text = os.path.join(OFFSET_PATH+"\\"+root, file)
Groups.insert(0, Group)
tree.write(UVPROJX_PATH, encoding='utf-8', xml_declaration=True)
elif KIND == '.h':
IncludePath = root.find("Targets").find("Target").find("TargetOption").find("TargetArmAds").find("Cads").find("VariousControls").find("IncludePath")
if IncludePath.text == None:
IncludePath.text = ""
h_list=[]
for root, dirs, files in os.walk(SOURCES_ROOT):
for file in files:
if file.endswith(KIND):
h_list.append(OFFSET_PATH+"\\"+root)
#print(set(h_list))
for path in set(h_list):
print(path)
IncludePath.text = IncludePath.text + ";" + path
tree.write(UVPROJX_PATH, encoding='utf-8', xml_declaration=True)
else:
print("KIND INPUT ERROR")
鏈接
: 陸續更新中...