0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Windowsでhead、tailするバッチ例

Last updated at Posted at 2024-09-30

単発小ネタ Windowsバッチ

20240930_Windowsでhead、tailするバッチ例

機能

  • bashのheadやtailのように、Windowsのコマンドプロンプトで対象ファイルの先頭行、末尾行を出力する
  • 第一引数 : 対象ファイル #必須
  • 第二引数 : 希望行数 #任意。デフォルト5行
  • batファイルのディレクトリにPath通せば、headとかtailでコマンド打てるようになります
head.bat
@echo off
if "%1" == "" GOTO :ERR
if "%2" == "" (set LNUM=5) else (set /a LNUM=%2)

echo.
echo   ** head start ** type head %LNUM% lines **
echo **** **** **** **** 
setlocal enabledelayedexpansion
for /f "tokens=1,2,3 usebackq" %%i in (`find /v /c "" %1`) do set LCTR=%%k

set /a CTR=0

for /f "tokens=1* delims=:" %%i in ('findstr /n "^" %1') do (
if "!CTR!" == "%LNUM%" goto :ENDX
if "%%j" == "" (echo. ) else (echo %%j)
set /a CTR+=1
)

:ENDX
echo **** **** **** **** 
echo   ** head end **
echo   ** cf : %1 has %LCTR% lines.
echo.
exit /b

:ERR
exit /b
tail.bat
@echo off
if "%1" == "" GOTO :ERR
if "%2" == "" (set LNUM=5) else (set /a LNUM=%2)
echo.
echo   ** tail start ** type tail %LNUM% lines **
echo **** **** **** **** 
for /f "tokens=1,2,3 usebackq" %%i in (`find /v /c "" %1`) do set LCTR=%%k
set /a STCTR=%LCTR%-%LNUM%

more +%STCTR% %1

:ENDX
echo **** **** **** **** 
echo   ** tail end **
echo   ** cf : %1 has %LCTR% lines.
echo.
exit /b

:ERR
exit /b

その他

  • 付加情報不要なら開始終了のecho削ってください。
  • cmderとか導入できれば、或いはwslとか使えれば特に困ることないんですけどね。オフラインのwindows環境もありますよね、ってことで。

アプローチを整理してみたので、良ければご確認ください。

https://qiita.com/kubo4ka/items/6f07bddab368329a1836

以上

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?